import React from 'react';
import { Button, Card, Col, DatePicker, Form, Row, message } from 'antd';
import { useContext, useEffect } from 'react';
import { ContractOppositeCountContext } from '../common';
import { SearchOutlined, ReloadOutlined } from '@ant-design/icons';

import pageStyles from '@/common/pageLayout.less';
import DeptPosLinkageUser from '@/components/DeptPosLinkageUser';
import moment from 'moment';
import { reportOppositeByStepService } from '../services';
const { RangePicker }: any = DatePicker;

export const OppositeSearchFormView: React.FC<ContractAllCountAPI.IOppositeSearchFormView> = ({
  changeStepType,
  curRes,
  setOppositeSearchInfo,
  countSearchForm,
}) => {
  /** 获取上下文 */
  const { styleFixCls, reportByStepRun, stepTypeValue } = useContext(ContractOppositeCountContext);

  /** 初始化搜索 */
  useEffect(() => {
    onSearch();
    isSearchStep();
  }, []);

  /** 统计回调 */
  const allCountCallback = (res: any) => {
    if (res && res?.msgFlag) {
      setOppositeSearchInfo(res?.obj);
    } else {
      message.error(res?.msg);
    }
  };

  /** 引入接口 */
  const { reportOppositeByStepRun } = reportOppositeByStepService(curRes, allCountCallback);

  /** 搜索 */
  const onSearch = () => {
    const searchPayload: Record<string, any> = countSearchForm?.getFieldsValue();
    let stepStr: number = 2;
    if (stepTypeValue == '月') {
      stepStr = 2;
    } else if (stepTypeValue == '年') {
      stepStr = 3;
    }
    let params: Record<string, any> = {
      ...searchPayload,
      choiceStyle: stepStr,
    };
    if (searchPayload?.supplierID) {
      reportOppositeByStepRun(params);
    } else {
      reportByStepRun(params);
    }
  };

  /** 刷新 */
  const reloadSearch = () => {
    countSearchForm?.resetFields();
    setOppositeSearchInfo({});
    onSearch();
  };

  /** 判断当前步长 */
  const isSearchStep = () => {
    const [createTimeStart, createTimeEnd] = countSearchForm?.getFieldValue('timeRanges');
    const oneYearRang = moment?.duration(createTimeEnd.diff(createTimeStart));
    if (oneYearRang?.asYears() > 1) {
      changeStepType('年');
    } else {
      changeStepType('月');
    }
  };

  return (
    <Card title="统计条件" className={`${styleFixCls}searchFormDiv`} bodyStyle={{ padding: '10px' }}>
      <div style={{ padding: '0px' }} className={pageStyles['fromView-styles']}>
        <Form form={countSearchForm} className={`${styleFixCls}searchFormDiv-formBox`}>
          <Row gutter={[8, 0]}>
            <DeptPosLinkageUser
              formRef={countSearchForm}
              colSpan={6}
              isNO_label={false}
              org_label={'申请部门/单位'}
              user_label="员工"
              orgamParams={{ params: 0, flowType: 'null' }}
              isNO_search={true}
              notUser={false}
              isDeptRequired={true}
              isUserRequired={false}
              isNo_selectCompany={false}
              isNO_selectDepartment={true}
              isNo_selectPosition={false}
              formCompanyID="companyID"
              formDepartmentID="departmentID"
              formPositionID="positionID"
              formUserID="userID"
              isNO_showPosition={false}
              // isNo_orgSelectChecks={true}
              // isNo_userSelectChecks={true}
            />
            {/* <Col span={6}>
              <Form.Item name="supplierID">
                <Select placeholder="合同相对方" loading={oppositeLoading} mode="multiple" maxTagCount={1}>
                  {oppositeDataRows?.map((item: any) => {
                    return (
                      <Select.Option value={item?.id} key={item?.id}>
                        {item?.oppositeName}
                      </Select.Option>
                    );
                  })}
                </Select>
              </Form.Item>
            </Col> */}
            <Col span={10}>
              <Form.Item name="timeRanges" initialValue={[moment().startOf('year'), moment().endOf('year')]}>
                <RangePicker
                  style={{ width: '100%' }}
                  format="YYYY-MM-DD"
                  placeholder={['开始日期', '结束日期']}
                  ranges={{
                    本年: [moment().startOf('year'), moment().endOf('year')],
                    近三年: [moment().subtract(3, 'years').startOf('year'), moment().endOf('year')],
                    近五年: [moment().subtract(5, 'years').startOf('year'), moment().endOf('year')],
                  }}
                  onChange={() => {
                    isSearchStep();
                  }}
                  allowClear={false}
                />
              </Form.Item>
            </Col>

            <Col span={8} style={{ textAlign: 'right' }}>
              <Button onClick={onSearch} icon={<SearchOutlined />} type="primary" style={{ marginRight: 8 }}>
                查询
              </Button>
              <Button onClick={reloadSearch} icon={<ReloadOutlined />}>
                重置
              </Button>
            </Col>
          </Row>
        </Form>
      </div>
    </Card>
  );
};
